# -*- coding: utf-8 -*-
import paho.mqtt.client as mqtt
import json
import datetime
import threading
import time
import gistool

datalist = []

i = 0
while i < 2000:
    datalist.append(i)
    i += 1

data = {"array": datalist}


class MqttClientNode(object):
    def __init__(self, vehicleid, host, port, path):
        self.host = host
        self.port = port
        self.client_id = vehicleid
        self.client = mqtt.Client(self.client_id)
        self.client.username_pw_set("admin", "admin@hrg2019")
        self.client.on_connect = self.on_connect
        self.client.on_message = self.on_message
        self.client.on_subscribe = self.on_subscribe
        self.client.on_disconnect = self.on_disconnect
        self.pub_topic = ""
        self.filepath = path

    def loop_forver(self):
        lp = Loopthread(self)
        lp.start()

    def connect_host(self):
        try:
            self.client.connect(self.host, self.port, 60)  # 60s
        except Exception as e:
            print(e)

    def subscribe(self, topic):
        try:
            self.client.subscribe(topic)
        except Exception as e:
            print(e)

    def on_connect(self, client, userdata, flags, rc):
        print("%s Connected with result code " % self.client_id)

    def on_subscribe(self, client, userdata, mid, granted_qos):
        print("On Subscribed: qos = %d" % granted_qos)

    def on_disconnect(self, client, userdata, rc):
        if rc != 0:
            print("Unexpected disconnection %s" % rc)

    def on_message(self, client, userdata, msg):
        # print("主题:" + msg.topic + " 消息:" + str(msg.payload, encoding='utf-8'))
        print("节点:%s 接收数据，总共:%d字节" % (self.client_id, len(str(msg.payload, encoding='utf-8'))))

    def pub_data(self):
        pbt = Pubthread(self, self.filepath)
        pbt.start()


class Loopthread(threading.Thread):
    def __init__(self, mqttnode):
        threading.Thread.__init__(self)
        self.mqtt_node = mqttnode

    def run(self):
        self.mqtt_node.client.loop_forever()


# class Pubthread(threading.Thread):
#     def __init__(self, mqttnode):
#         threading.Thread.__init__(self)
#         self.mqtt_node = mqttnode
#
#     def run(self):
#         while True:
#             data["carid"] = self.client_id
#             param = json.dumps(data)
#             self.mqtt_node.client.publish(self.mqtt_node.pub_topic, payload=param, qos=0)  # 发送消息
#             print("节点：%s 发送数据总计:%d字节" % (self.client_id, len(param)))
#             time.sleep(1)


def convertlattitude(data):
    temp = str(data)
    ind = temp.find('.')
    d = temp[0:ind]
    m = temp[ind:len(temp)]
    return d + str(float(m) * 60)


def convertlontitude(data):
    temp = str(data)
    ind = temp.find('.')
    d = temp[0:ind]
    m = temp[ind:len(temp)]
    return d + str(float(m) * 60)


class Pubthread(threading.Thread):
    def __init__(self, mqttnode, filepath):
        threading.Thread.__init__(self)
        self.mqtt_node = mqttnode
        self.path = filepath

    def run(self):
        xl, yl = gistool.explainshp_without_proj(self.path)
        while True and len(xl) > 0:
            lon = convertlontitude(xl.pop(0))
            lat = convertlattitude(yl.pop(0))
            param = "V0_0_0,6201,%s,6203,%s" % (lat, lon)

            self.mqtt_node.client.publish("/PPT/high/%s" % self.mqtt_node.client_id, payload=param, qos=0)  # 发送消息

            param2 = "V0_0_0,3f03,1,4302,1,4601,132"
            self.mqtt_node.client.publish("/WOK/%s" % self.mqtt_node.client_id, payload=param2, qos=0)  # 发送消息
            time.sleep(1)
